package cn.imokay.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;

//指定数值区间求和
public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyRecursiveTask task = new MyRecursiveTask(0, 100000);
        System.out.println(task.fork().get());
    }

}

class MyRecursiveTask extends RecursiveTask<Integer> {
    private static  int NUMBER = 10;
    private int start;
    private int end;

    public MyRecursiveTask(int start, int end) {
        this.start = start;
        this.end = end;
        NUMBER = (end - start)/10;
    }

    @Override
    protected Integer compute() {
        System.out.println(Thread.currentThread().getName());
        if (end - start <= NUMBER) {
            int sum = 0;
            for (int i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else{
            int middle = (start + end) / 2;
            MyRecursiveTask left = new MyRecursiveTask(start, middle);
            MyRecursiveTask right = new MyRecursiveTask(middle + 1, end);
            left.fork();
            right.fork();
            return left.join() + right.join();
        }
    }
}
